<template>
  <div class="tags-view-container">
    <div class="tags-view-wrapper">
      <el-tag
        v-for="tag in filteredViews"
        :key="tag.path"
        :closable="tag.path !== '/dashboard'"
        :effect="isActive(tag) ? 'dark' : 'plain'"
        :class="{'is-active': isActive(tag)}"
        @click="toView(tag)"
        @close="closeTag(tag)"
        @contextmenu.prevent="openMenu(tag, $event)"
        class="tags-view-item"
      >
        {{ tag.title }}
      </el-tag>
    </div>
    
    <!-- 右键菜单 -->
    <ul v-show="visible" :style="{left: left+'px', top: top+'px'}" class="contextmenu">
      <li @click="refreshSelectedTag(selectedTag)">刷新页面</li>
      <li v-if="selectedTag && selectedTag.path !== '/dashboard'" @click="closeSelectedTag(selectedTag)">关闭当前</li>
      <li @click="closeOtherTags(selectedTag)">关闭其他</li>
      <li @click="closeAllTags">关闭所有</li>
    </ul>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 已访问的视图
const visitedViews = ref([])

// 右键菜单相关变量
const visible = ref(false)
const top = ref(0)
const left = ref(0)
const selectedTag = ref(null)

// 路由元信息获取标题
const getTitle = (route) => {
  let title = route.name || route.path
  if (route.meta && route.meta.title) {
    title = route.meta.title
  }
  
  // 如果是仪表盘，显示为仪表盘，不显示路径
  if (route.path === '/dashboard') {
    return '仪表盘'
  }
  
  return title
}

// 过滤标签视图
const filteredViews = computed(() => {
  return visitedViews.value.filter(tag => {
    // 过滤掉路径为"/"的标签
    return tag.path !== '/';
  });
});

// 添加访问过的视图
const addVisitedView = (view) => {
  // 避免重复添加
  if (visitedViews.value.some(v => v.path === view.path)) return
  
  // 根据路由信息生成标签信息
  visitedViews.value.push(
    Object.assign({}, view, {
      title: getTitle(view)
    })
  )
}

// 关闭标签
const closeTag = (view) => {
  // 首页标签不允许关闭
  if (view.path === '/dashboard') return
  
  // 从已访问视图中移除
  const index = visitedViews.value.findIndex(v => v.path === view.path)
  if (index !== -1) {
    visitedViews.value.splice(index, 1)
  }
  
  // 如果关闭的是当前视图，需要导航到其他视图
  if (isActive(view)) {
    toLastView(visitedViews.value, view)
  }
}

// 关闭所有标签
const closeAllTags = () => {
  // 对于首页，我们总是保留的
  router.push('/dashboard')
  // 删除所有标签（除了首页）
  visitedViews.value = visitedViews.value.filter(tag => tag.path === '/dashboard')
  closeMenu()
}

// 关闭其他标签
const closeOtherTags = (view) => {
  router.push(view.path)
  visitedViews.value = visitedViews.value.filter(tag => 
    tag.path === view.path || tag.path === '/dashboard'
  )
  closeMenu()
}

// 关闭选中的标签
const closeSelectedTag = (view) => {
  closeTag(view)
  closeMenu()
}

// 刷新选中的标签
const refreshSelectedTag = (view) => {
  closeMenu()
  router.replace({
    path: '/redirect' + view.path
  })
}

// 打开右键菜单
const openMenu = (tag, e) => {
  const menuMinWidth = 105
  const offsetLeft = e.clientX
  const offsetWidth = e.target.offsetWidth
  const maxLeft = window.innerWidth - menuMinWidth
  const left = offsetLeft + 15

  top.value = e.clientY
  left.value = Math.min(maxLeft, left)
  visible.value = true
  selectedTag.value = tag
}

// 关闭右键菜单
const closeMenu = () => {
  visible.value = false
}

// 导航到最后一个视图
const toLastView = (visitedViews, view) => {
  const latestView = visitedViews.slice(-1)[0]
  if (latestView) {
    router.push(latestView.path)
  } else {
    // 如果没有标签了，导航到首页
    if (view.name === 'dashboard') {
      router.push('/dashboard')
    } else {
      router.push('/dashboard')
    }
  }
}

// 导航到标签对应的视图
const toView = (view) => {
  router.push(view.path)
}

// 检查标签是否为当前活动视图
const isActive = (view) => {
  return view.path === route.path
}

// 添加点击文档的事件监听，关闭右键菜单
onMounted(() => {
  // 首先确保有仪表盘标签，使用固定的标题"仪表盘"
  addVisitedView({ 
    path: '/dashboard', 
    meta: { title: '仪表盘' }, 
    name: 'dashboard' 
  })
  
  // 然后添加当前路由，但排除根路径和dashboard路径
  if (route.path !== '/dashboard' && route.path !== '/') {
    addVisitedView(route)
  }
  
  document.body.addEventListener('click', closeMenu)
})

// 监听路由变化，添加访问视图
watch(
  () => route.path,
  () => {
    // 不添加根路径和仪表盘路径的标签
    if (route.path !== '/' && route.path !== '/dashboard') {
      addVisitedView(route)
    }
  }
)
</script>

<style scoped>
.tags-view-container {
  height: 34px;
  width: 100%;
  background: #f5f7fa;
  border-bottom: 1px solid #d8dce5;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 0 3px 0 rgba(0, 0, 0, 0.04);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
  margin: 0;
}

.tags-view-wrapper {
  padding: 0 16px;
  height: 100%;
  display: flex;
  align-items: center;
  overflow-x: auto;
  white-space: nowrap;
  flex: 1;
}

.tags-view-wrapper::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.tags-view-wrapper::-webkit-scrollbar-thumb {
  background: #bababa;
  border-radius: 3px;
}

.tags-view-item {
  margin-right: 2px;
  cursor: pointer;
  height: 26px;
  line-height: 26px;
  border: 1px solid #d8dce5;
  padding: 0 8px;
  font-size: 12px;
  border-radius: 3px 3px 0 0;
  position: relative;
  bottom: -1px;
}

.tags-view-item:hover {
  opacity: 0.85;
}

.tags-view-item.is-active {
  background-color: #fff;
  border-bottom-color: #fff;
  color: #409eff;
}

.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 400;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
}

.contextmenu li {
  margin: 0;
  padding: 7px 16px;
  cursor: pointer;
}

.contextmenu li:hover {
  background: #eee;
}
</style>